package com.zhiche.lisa.lspm.service.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.zhiche.lisa.core.enums.SystemEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.redislog.RedisLogUtil;
import com.zhiche.lisa.lspm.dto.*;
import com.zhiche.lisa.lspm.vo.common.OriginationCityVO;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * Created by zhaoguixin on 2018/7/23.
 */
@Component
public class IntegrationUtil {

    private static String integrationToOtm;

    private static final Logger LOGGER = LoggerFactory.getLogger(IntegrationUtil.class);
    private String LSP_URI = "/carrier/lspExport";
    private String VEHICEL_URI = "/carrier/vehicleExport";
    private String DRIVER_URI = "/carrier/driverExport";

    @Value("${integration.url}")
    private String INTEGRATION_URL;
    @Value("${integration.socketTimeout}")
    private Integer socketTimeout;
    @Value("${integration.checkin_url}")
    private String CHECKIN_URL;
    @Value("${integration.origination_city_url}")
    private String ORIGINATION_CITY_URL;

    @Value("${logRedis.isTest}")
    private boolean isTest;

    @Value("${integrationToOtm}")
    private void setIntegrationToOtm(String integrationToOtm) {
        IntegrationUtil.integrationToOtm = integrationToOtm;
    }

    public static String getIntegrationToOtm() {
        return integrationToOtm;
    }

    public String exportLspToOTM(LspInfoDTO lspInfoDTO) {
        LOGGER.info("IntegrationUtil.exportLspToOTM Params:" + lspInfoDTO);
        String result = HttpClientUtil.postJson(INTEGRATION_URL + LSP_URI, null,
                JSON.toJSONString(lspInfoDTO), socketTimeout);
        LOGGER.info("IntegrationUtil.exportLspToOTM result:" + result);

        RedisLogUtil.addSysLogs(SystemEnum.LSPM.getCode(),SystemEnum.INTEGRATION.getCode(),"lsp"+lspInfoDTO.getId(),JSON.toJSONString(lspInfoDTO),"/carrier/lspExport",1,1,null,isTest);

        if (!StringUtils.isEmpty(result)) {
            RestfulResponse<String> restfulResponse = JSON.parseObject(result,
                    new TypeReference<RestfulResponse<String>>() {
                    });
            if (Objects.nonNull(restfulResponse) && restfulResponse.getCode() == 0) {
                return restfulResponse.getData();
            }
        }
        return null;
    }

    /**
     * 导出车辆至OTM
     */
    public void exportVehicleToOTM(VehicleDTO vehicleDTO) {
        LOGGER.info("IntegrationUtil.exportVehicleToOTM param {}", vehicleDTO);
        if (Objects.isNull(vehicleDTO)) {
            throw new BaseException("IntegrationUtil.exportVehicleToOTM 车辆不能为空！");
        }
        String otmJson = JSONObject.toJSONString(vehicleDTO);
        LOGGER.info("IntegrationUtil.exportVehicleToOTM url: {},param:{}", INTEGRATION_URL + VEHICEL_URI, otmJson);
        String result = null;

        try {
            result = HttpClientUtil.postJson(INTEGRATION_URL + VEHICEL_URI, null,
                    otmJson, socketTimeout);

            RedisLogUtil.addSysLogs(SystemEnum.LSPM.getCode(),SystemEnum.INTEGRATION.getCode(),"carrier"+vehicleDTO.getId()+"",JSON.toJSONString(vehicleDTO),"/carrier/vehicleExport",1,1,null,isTest);

            LOGGER.info("IntegrationUtil.exportVehicleToOTM result {}", result);
        } catch (Exception e) {
            LOGGER.error("IntegrationUtil.exportVehicleToOTM 连接超时 {}", e);
            throw new BaseException("IntegrationUtil.exportVehicleToOTM 连接超时-<");
        }
        if (StringUtils.isEmpty(result)) {
            throw new BaseException("车辆导出至OTM失败,未响应");
        }
    }

    /**
     * 导出车辆至OTM
     */
    public void exportDriverToOTM(DriverDTO driverDTO) {
        if (Objects.isNull(driverDTO)) {
            throw new BaseException("司机不能为空！");
        }
        String otmJson = JSONObject.toJSONString(driverDTO);
        LOGGER.info("IntegrationUtil.exportDriverToOTM url:{} Params:{}", INTEGRATION_URL + DRIVER_URI, otmJson);
        String result = null;
        try {
            result = HttpClientUtil.postJson(INTEGRATION_URL + DRIVER_URI, null,
                    otmJson, socketTimeout);
            LOGGER.info("IntegrationUtil.exportDriverToOTM result:{}", result);
        } catch (Exception e) {
            LOGGER.error("IntegrationUtil.exportDriverToOTM 连接超时 {}", e);
            throw new BaseException("IntegrationUtil.exportDriverToOTM 连接超时-<");
        }
        if (StringUtils.isEmpty(result)) {
            throw new BaseException("司机导出至OTM失败,未响应");
        }
    }

    /**
     * 导出报班至OTM
     */
    public RestfulResponse exportCheckin(DriverCheckinDTO driverCheckinDTO) {
        if (Objects.isNull(driverCheckinDTO)) {
            throw new BaseException("司机报班不能为空！");
        }
        String jsonStr = JSON.toJSONString(driverCheckinDTO);
        //new Thread(() -> {
            LOGGER.info("IntegrationUtil.exportCheckin url:{}, param: {}", INTEGRATION_URL + CHECKIN_URL, jsonStr);
            try {
                String result = HttpClientUtil.postJson(INTEGRATION_URL + CHECKIN_URL, null,
                        jsonStr, socketTimeout);
                //String result="{\"code\": -1,\"message\": \"转换失败\",\"data\": null}";
                if (!StringUtils.isEmpty(result)){
                    JSONObject jsonObject = JSON.parseObject(result);
                    int code = jsonObject.getIntValue("code");
                    if (code != 0) {
                        throw new BaseException("司机报班-->推送OTM失败" + jsonObject.getString("message"));
                    }
                }else {
                    throw new BaseException("司机报班-->推送OTM失败,请重新报班");
                }
                LOGGER.info("IntegrationUtil.exportCheckin result:{}", result);
            } catch (Exception e) {
                LOGGER.error("IntegrationUtil.exportCheckin 连接超时:{}", e);
                throw new BaseException("司机报班-->推送OTM失败");
            }
       // }).start();
        return null;
    }

    /**
     * 获取起运点城市
     */
    public RestfulResponse<List<OriginationCityVO>> getOriginationCity(String cityName) {
        if (StringUtils.isEmpty(cityName)) throw new BaseException("城市名称不能为空！");
        List<NameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair("cityName", cityName));
        String result = HttpClientUtil.get(INTEGRATION_URL + ORIGINATION_CITY_URL, null, params, socketTimeout);
        if (!StringUtils.isEmpty(result)) {
            RestfulResponse<List<OriginationCityVO>> restfulResponse = JSON.parseObject(result,
                    new TypeReference<RestfulResponse<List<OriginationCityVO>>>() {
                    });
            List<OriginationCityVO> list = restfulResponse.getData();
            list.forEach(originationCityVO -> {
                String provinceCode = originationCityVO.getProvinceCode() + String.format("%1$04d", 0);
                String cityCode = originationCityVO.getCityCode() + String.format("%1$02d", 0);
                originationCityVO.setProvinceCode(provinceCode);
                originationCityVO.setCityCode(cityCode);
            });
            return restfulResponse;
        }
        throw new BaseException("获取起运点城市失败");
    }

    //转换板车类型名字
    public String getTrailerTypeName(String trailerTypeName) {
        if (!StringUtils.isEmpty(trailerTypeName)) {
            if (trailerTypeName.equals("三位平板")) {
                return "平板三位板";
            }
            if (trailerTypeName.equals("四位平板")) {
                return "平板四位板";
            }
            if (trailerTypeName.equals("六位平板")) {
                return "六位车";
            }
            if (trailerTypeName.equals("单车")) {
                return "单车";
            }
            if (trailerTypeName.equals("中置轴")) {
                return "中置轴";
            }
            if (trailerTypeName.equals("七位平板")) {
                return "七位车";
            }
            if (trailerTypeName.equals("人送地跑")) {
                return "人送地跑";
            }
            if (trailerTypeName.equals("铁路J车")) {
                return "铁运J车";
            }
            if (trailerTypeName.equals("铁路板架厢")) {
                return "铁运板架箱";
            }
            if (trailerTypeName.equals("救援车")) {
                return "救援车";
            }
            if (trailerTypeName.equals("船运")) {
                return "水运";
            }
            if (trailerTypeName.equals("五位平板")) {
                return "平板五位板";
            }
            if (trailerTypeName.equals("八位平板")) {
                return "八位车";
            }
        }
        return "六位车";
    }

    public String getServiceType(String serviceType) {
        if (!StringUtils.isEmpty(serviceType)) {
            if (serviceType.contains("板车运输")) {
                serviceType = serviceType.replaceAll("板车运输", "公路");
            }
            if (serviceType.contains("铁路运输")) {
                serviceType = serviceType.replaceAll("铁路运输", "铁运");
            }
            if (serviceType.contains("人送地跑")) {
                serviceType = serviceType.replaceAll("人送地跑", "人送");
            }
            if (serviceType.contains("船运")) {
                serviceType = serviceType.replaceAll("船运", "水运");
            }
            return serviceType.replaceAll(";", ",");
        } else {
            return "公路";
        }
    }
}
